<?php

    require_once('classes/LeproHelper.class.php');
    
    if(!function_exists("echobig")) {
        function echobig($string, $bufferSize = 8191) { // echo variant from http://php.net/manual/en/function.echo.php#52881, #50401
            // suggest doing a test for Integer & positive bufferSize
            for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
                echo substr($string,$start,$bufferSize);
            }
        }
    }    
    
    if(!function_exists("bcmul")) { // http://php.net/manual/en/function.bcmul.php#75758
        function bcmul($_ro, $_lo, $_scale=0)
        {
            return round($_ro*$_lo, $_scale);
        }
    }
    
    if(!function_exists("bcdiv")) { // http://php.net/manual/en/function.bcdiv.php#84255
        function bcdiv($_ro, $_lo, $_scale=0)
        {
            return round($_ro/$_lo, $_scale);
        }
    }
    
    if(!function_exists("not_empty")) {
        function not_empty($str) {
            return ($str != '');
        }
    }
    
    if(!function_exists("format_time")) {
        function format_time($time) {
            if ($time == '') return '';
            if (preg_match("/^(\d{1,2})\s(\d{1,2})\s(\d{4})\s(\d{1})\s(\d{1,2})\s(\d{2})\s(\d{2})$/", 
                      date("j n Y N G i s", (int)$time), $matches)) {;
                return array(
                    'day' => $matches[1],
                    'month' => $matches[2],
                    'year' => $matches[3],
                    'wday' => $matches[4],
                    'hour' => $matches[5],
                    'minute' => (int)$matches[6],
                    'second' => (int)$matches[7]
                );
            } else return null; 
        }
    }            

    if(!function_exists("userIdConvertor")) {
        function userIdConvertor($internalId) {
            return LeproHelper::getExternalUserId($internalId, '.');
        }
    }
    
    if(!function_exists("nvardump")) {
    	function nvardump($obj, $show_r=false) {
            echo "<pre>";
            if ($show_r) print_r($obj);
            if (!$show_r) var_dump($obj);
            echo "</pre><br/>";     		
    	}
    }
    
    if(!function_exists("strlen_utf8")) {
        function strlen_utf8($s) {
            return strlen(utf8_decode($s));
        }
    }    
    
    if(!function_exists("substr_utf8")) {
	   function substr_utf8($str,$from,$len) {
		  # utf8 substr
		  # www.yeap.lv
		  return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
		                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
		                       '$1',$str);
	      }
    }    

    if(!function_exists("imagettftextwrap")) {  // http://php.net/manual/en/function.imagettfbbox.php#65691
    	
		function imagewordwrapbbox($text, $angle, $width=650, $fontSize=10, $font) {
		    $words = split(' ', $text);
		    $lines = array();
		    $line = '';
		
		    foreach ($words as $word) {
		        $box = imagettfbbox($fontSize, $angle, $font, $line.$word);
		        $size = $box[4] - $box[0];
		        if ($size > $width) {
		            $lines[] = trim($line);
		            $line = '';
		        }
		        $line .= $word.' ';
		    }
		    $lines[] = trim($line);
		
		    $dimensions = imagettfbbox($fontSize, $angle, $font, 'AJLMYabdfghjklpqry019`@$^&*(,');
		    $lineHeight = $dimensions[1] - $dimensions[5];
		
		    return array($lineHeight, $lines, $lineHeight * count($lines));
		}
		
		
		function imagettftextwrap($image, $fontSize = 10, $angle, $x=0, $y=0, $width, $color, $font, $text) {
		    
			$data = imagewordwrapbbox($text, $angle, $width, $fontSize, $font);
		
		    foreach ($data[1] as $key=>$line) {
		        $locX = $x;
		        $locY = $y + ($key * $data[0]); 
		        imagettftext($image, $fontSize, $angle, $locX, $locY, $color, $font, $line);
		    }
		
		    return $data;
		}
		
		function imagetextcolors($text, $colorsArr, $is_utf8=false) {
			
			$strippedText = '';
			
			$colorsData = array();
			$matchesNum = preg_match_all('|<(\d+)>(.+)</\\1(>)|', $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
            //$splittedData = preg_split("/<(\d+)>(.+)<\/\1>/", $text, -1, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_DELIM_CAPTURE);
            /* while (preg_match("/<(\d+)>(.+)</\1>/", $text) > 0) {
                
            } */			
			
			$prevLastPos = 0;
			
			foreach ($matches as $matchData) {				
				$startPos = $matchData[0][1];
				$colorNum = $matchData[1][0];
				$textMatched = $matchData[2][0];
				$lastPos = $matchData[3][1] + strlen($matchData[3][0]);
				$strippedText .= substr($text, $prevLastPos, $startPos - $prevLastPos);
                $colorsData[] = array(
                    'color' => $colorNum,
                    'startPos' => $is_utf8 ? strlen_utf8($strippedText) : strlen($strippedText),
                    'blockLen' => $is_utf8 ? strlen_utf8($textMatched) : strlen($textMatched)
                );
				$strippedText .= $textMatched;
				$prevLastPos = $lastPos;
			}
			
			$strippedText .= substr($text, $prevLastPos);
			return array($strippedText, $colorsData);
		}
		
		function isblockstartsonline($lineStart, $lineEnd, $blockStart) {
			return ($blockStart >= $lineStart) && ($blockStart < $lineEnd);
		}
		
		function isblockendsonline($lineStart, $lineEnd, $blockStart, $blockLength) {
			$blockLastPos = $blockStart + $blockLength;
            return ($blockLastPos > $lineStart) && ($blockLastPos <= $lineEnd);
        }
		
		function imagettftextcoloredwrap($image, $fontSize = 10, $angle, $x=0, $y=0, $width, $colorsArr, $font, $text, $defaultColor=null, $is_utf8=false) {

			$defaultColor = $defaultColor ? $defaultColor : imagecolorallocate($image, 0, 0, 0);
			
			$coloringResult = imagetextcolors($text, $colorsArr, true);
			$strippedText = $coloringResult[0];
			$colorsData = $coloringResult[1];
            $data = imagewordwrapbbox($strippedText, $angle, $width, $fontSize, $font);
            
            $curlineend = 0;
            
            $lines = $data[1];
            $midlength = $data[0]; 

            $linesBlocks = array();
            
            reset($lines);
            
            while (($colorBlock = current($colorsData)) && 
                   (($curline = current($lines)) !== null)) {         	
            	$linekey = key($lines);
            	if (!array_key_exists($linekey, $linesBlocks)) {
            		$linesBlocks[$linekey] = array();
                    $curlinestart = $curlineend;
                    $linelength = $is_utf8 ? strlen_utf8($curline) : strlen($curline);
                    $curlineend += $linelength + ($linelength > 0 ? 1 : 0); // possible stripped space
            	}
                $blockStartPos = $colorBlock[startPos]; 
                $blockLength = $colorBlock[blockLen];
                $blockEnds = isblockendsonline($curlinestart, $curlineend, $blockStartPos, $blockLength);
                $blockStarts = isblockstartsonline($curlinestart, $curlineend, $blockStartPos);
                if ($blockStarts || $blockEnds) {
                	$blockAlignedStart = $blockStartPos - $curlinestart;
                	$blockAlignedEnd = $blockAlignedStart + $blockLength;
                	$blockData = array(
                	   'color' => $colorBlock[color],
                	   'start' => ($blockAlignedStart >= 0) ? $blockAlignedStart : 0,
                	   'end' => ($blockAlignedEnd >= $linelength) ? $linelength : $blockAlignedEnd
                	);
                	$linesBlocks[$linekey][] = $blockData;
                	
                }
                if (!($blockStarts && $blockEnds)) next($lines);
                if ($blockEnds) next($colorsData); 
            }
            
            while(next($lines)) {
            	$linesBlocks[key($lines)] = array();
            }
            
            // nvardump($linesBlocks, true);
            
            foreach ($lines as $key=>$line) {
            	$locX = $x;
                $locY = $y + ($key * $midlength);  
                //echo count($linesBlocks[$key]);
                $blocksData = $linesBlocks[$key]; 
                if (count($blocksData) == 0) {           
                    imagettftext($image, $fontSize, $angle, $locX, $locY, $defaultColor, $font, $line);
                } else {
                	$linepos = 0;
                	$linexpos = $locX;
                	$linelen = $is_utf8 ? strlen_utf8($line) : strlen($line);
                	foreach ($blocksData as $blockData) {
                		$blockLen = $blockData[end] - $blockData[start];
                		$prevTextLen = $blockData[start] - $linepos;
                		$prevText = $is_utf8 ? substr_utf8($line, $linepos, $prevTextLen) : substr($line, $linepos, $prevTextLen);
                		$coloredText = $is_utf8 ? substr_utf8($line, $blockData[start], $blockLen) : substr($line, $blockData[start], $blockLen);
                		$prevTextBox = imagettfbbox($fontSize, $angle, $font, $prevText);
                		$coloredTextBox = imagettfbbox($fontSize, $angle, $font, $coloredText);
                		$coloredTextX = $linexpos + $prevTextBox[4];
                		imagettftext($image, $fontSize, $angle, $linexpos, $locY, $defaultColor, $font, $prevText);
                		imagettftext($image, $fontSize, $angle, $coloredTextX, $locY, $colorsArr[$blockData[color]], $font, $coloredText);
                        $linepos = $blockData[end];
                        $spaceb = imagettfbbox($fontSize, $angle, $font, ' ');                		
                        $linexpos += $prevTextBox[4] + $coloredTextBox[4] + $spaceb[4];                		
                	}
                	if ($linepos < $linelen) {
                		$textLeftLen = $linelen - $linepos;                		 
                		$textLeft = $is_utf8 ? substr_utf8($line, $linepos, $textLeftLen) : substr($line, $linepos, $textLeftLen);
                        imagettftext($image, $fontSize, $angle, $linexpos, $locY, $defaultColor, $font, $textLeft);                		
                	}
                }
            }
        
            return $data;
        }

    }

    if(!function_exists("unlinkRecursive")) { // http://php.net/manual/en/function.unlink.php#87045
    /**
	 * Recursively delete a directory
	 *
	 * @param string $dir Directory name
	 * @param boolean $deleteRootToo Delete specified top-level directory as well
	 */
		function unlinkRecursive($dir, $deleteRootToo=false)
		{
		    if(!$dh = opendir($dir))
		    {
		        return;
		    }
		    while (false !== ($obj = readdir($dh)))
		    {
		        if($obj == '.' || $obj == '..')
		        {
		            continue;
		        }
		
		        if (!unlink($dir . '/' . $obj))
		        {
		            unlinkRecursive($dir.'/'.$obj, true);
		        }
		    }
		
		    closedir($dh);
		   
		    if ($deleteRootToo)
		    {
		        rmdir($dir);
		    }
		   
		    return;
		} 
    }
?>